﻿//=====================================================================
//
//  File:      LargeStringUDT.cs
//  Summary:   Shows how to fetch rows with LargeUDT types from a result set.
//  Date:      July 3, 2008
//
//---------------------------------------------------------------------
//
//  This file is part of the Microsoft SQL Server Code Samples.
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation.  See these other
//materials for detailed information regarding Microsoft code samples.
//
//THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
//ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
//THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//
//===================================================================== 

using System;
using System.Data;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedType(Format.UserDefined, IsFixedLength = false, MaxByteSize = -1, IsByteOrdered = true)]
public class LargeStringUDT : INullable, IBinarySerialize {
   private bool _isNull;
   private string _largeString;

   public bool IsNull {
      get {
         return (_isNull);
      }
   }

   public static LargeStringUDT Null {
      get {
         LargeStringUDT lsUDT = new LargeStringUDT();
         lsUDT._isNull = true;
         return lsUDT;
      }
   }

   public override string ToString() {
      if (this.IsNull)
         return "NULL";
      else
         return _largeString;
   }

   [SqlMethod(OnNullCall = false)]
   public static LargeStringUDT Parse(SqlString s) {
      if (s.IsNull)
         return Null;

      LargeStringUDT lsUDT = new LargeStringUDT();
      lsUDT._largeString = s.Value;
      return lsUDT;
   }

   public String LargeString {
      get {
         return this._largeString;
      }

      set {
         _largeString = value;
      }
   }

   public void Read(System.IO.BinaryReader r) {
      _isNull = r.ReadBoolean();
      if (!_isNull)
         _largeString = new String(r.ReadChars(r.ReadInt32()));
   }

   public void Write(System.IO.BinaryWriter w) {
      w.Write(_isNull);
      if (!_isNull) {
         w.Write(_largeString.Length);
         for (int i = 0; i < _largeString.Length; ++i)
            w.Write(_largeString[i]);
      }
   }

   private bool ValidateHugeString() {
      return true;
   }
}